package com.cgdata.morethreadselectdb;

import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class ThreadQueryService {

    public List<List> getMaxResult(String table) throws Exception {
        long start = System.currentTimeMillis();
        List<List> result = new ArrayList<>();
        //查询数据库总数量
//        Integer count = Db.queryInt(" select count(1) from tablename ");
        Integer count = 60050;//模拟数据库查询出来的总条数
        int num = 4000;//一次查询多少条
        //需要查询的次数
        int times = count / num;
        if (count % num != 0) {
            times = times + 1;
        }
        //开始页数
        int bindex = 0;
        List<Future> list = new ArrayList<>();
        //定义固定长度的线程池，防止线程过多
        ExecutorService executorService = Executors.newFixedThreadPool(15);
//        executorService.execute(()->{
//            System.out.println("aaa");
//        });
        //循环查询
        for (int i = 0; i < times; i++) {
            ThreadQuery threadQuery = new ThreadQuery(bindex,num,"");
            Future<List> future = executorService.submit(threadQuery);
            list.add(future);
            //多线程同时查询，保证开始页数的原子性
            synchronized (this){
                bindex = bindex+num;
            }
        }
        for (Future<List> future : list) {
            result.addAll(future.get());
        }
        executorService.shutdown();
        //排序
        List<List> result1 = result.parallelStream().sorted().collect(Collectors.toList());
        long end = System.currentTimeMillis();
        System.out.println("线程查询数据用时："+(end-start)+"ms");
        System.out.println("aaaaa");
        System.out.println("bbbbb");
        return result1;
    }


}
